package com.block.job.service.channelcost;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.service.LogFactory;
import com.block.db.entity.ChannelCountInfo;
import com.block.db.mapper.ChannelCountInfoMapper;
import com.block.job.model.KeyInfoDTO;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ChannelRongyaoCostService {

    private static final Logger log = LogFactory.getJobLog();

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Resource
    ChannelCountInfoMapper channelCountInfoMapper;

    private static Map<String, KeyInfoDTO> keyInfoDTOMap = new HashMap<>();

    static {
        keyInfoDTOMap.put("rongyao", new KeyInfoDTO("rongyao", "1854822737837948928", "aEo5qHJ09zNX4q2drZ9ogUhmpLG88VTa"));

    }

    public void getAccountCost() {

        for (String key : keyInfoDTOMap.keySet()) {
            KeyInfoDTO keyInfoDTO = keyInfoDTOMap.get(key);

            this.getCost(keyInfoDTO);
        }
    }

    public void getCost(KeyInfoDTO keyInfoDTO){

        String accessToken = this.getToken(keyInfoDTO);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("x-request-id", cn.hutool.core.lang.UUID.fastUUID().toString());
        headMap.put("Authorization", "Bearer "+accessToken);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("startTime", LocalDate.now().toString());
        bizMap.put("endTime", LocalDate.now().toString());

        String requestUrl = "https://ads.cloud.honor.com/openapi/v2_1/account/consume/list";

        String response = HttpUtil.createPost(requestUrl)
                .headerMap(headMap, true)
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("荣耀成本：{}", response);
        JSONObject resultObject = JSON.parseObject(response);
        Integer code = resultObject.getInteger("code");
        if (code == 0){

            JSONArray jsonArray = resultObject.getJSONArray("data");
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            BigDecimal totalConsume = jsonObject.getBigDecimal("totalConsume");
            BigDecimal costAmount =  totalConsume.divide(new BigDecimal(1000000));

            transactionTemplate.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus status) {

                    String dateInfo = LocalDate.now().toString();
                    ChannelCountInfo channelCountInfo = channelCountInfoMapper.getEntityByChannelCodeAndDateInfo(keyInfoDTO.getChannelCode(), dateInfo);
                    if (ObjectUtil.isNotEmpty(channelCountInfo)){
                        ChannelCountInfo updateEntity = new ChannelCountInfo();
                        updateEntity.setId(channelCountInfo.getId());
                        updateEntity.setUvCost(costAmount);
                        channelCountInfoMapper.updateById(updateEntity);
                    }
                    return null;
                }
            });
        }
        return;
    }

    public String getToken(KeyInfoDTO keyInfoDTO) {
        String redisKey = StrUtil.format(RedisKeyConstant.RONGYAO_CHANNEL_ACCESS_TOKEN, keyInfoDTO.getClientId());
        String token = stringRedisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("grant_type", "client_credentials");
        bizMap.put("client_id", keyInfoDTO.getClientId());
        bizMap.put("client_secret", keyInfoDTO.getClientSecret());

        String requestUrl = "https://iam.developer.hihonor.com/auth/realms/advertisement/protocol/openid-connect/token";

        String response = HttpUtil.createPost(requestUrl)
                .form(bizMap)
                .execute().body();

        JSONObject jsonObject = JSON.parseObject(response);
        String access_token = jsonObject.getString("access_token");

        if (ObjectUtil.isEmpty(access_token)){
            throw new RuntimeException("荣耀获取accessToken失败："+response);
        }

        // 更新access token 缓存信息
        stringRedisTemplate.opsForValue().set(redisKey, access_token, 50, TimeUnit.MINUTES);
        return access_token;
    }

}
